package com.epam.qanda.web.servlet.questionlist;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.epam.qanda.db.model.AnswerUser;
import com.epam.qanda.db.model.QuestionCategory;
import com.epam.qanda.db.service.AnswerUserService;
import com.epam.qanda.db.service.QuestionCategoryService;

public class ShowQuestionAnswersServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Integer COUNT = 10;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int qId = Integer.parseInt(request.getParameter("question").trim());
		QuestionCategory question = new QuestionCategoryService().getByQuestionId(qId);
		List<AnswerUser> answers = new AnswerUserService().getAllAnswerUsers(qId);
		
		Integer offset = 0;
		String off = request.getParameter("offset");
		if (off != null) {
			offset = Integer.parseInt(off.trim());
			request.removeAttribute("offset");
		}

		List<AnswerUser> newAnswers = new ArrayList<AnswerUser>();
		for (int i = offset; i < offset + COUNT; i++) {
			if (i < 0 || i >= answers.size())
				continue;
			newAnswers.add(answers.get(i));
		}
		
		
		request.setAttribute("offset", offset);
		request.setAttribute("size", answers.size());
		
		request.setAttribute("question", question);
		request.setAttribute("answers", newAnswers);
		request.getRequestDispatcher("WEB-INF/pages/questionPage.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
